/*
 * mcp9801.c
 *
 *  Created on: Oct 13, 2013
 *      Author: IEUser
 */


/******************************************************************************************
 *	Deklaracje dołączanych plików nagłówkowych i bibliotek								 *
 *****************************************************************************************/
#include <avr/io.h>

#include "mcp9801.h"

/******************************************************************************************
 *	Deklaracje zmiennych globalnych								                         *
 *****************************************************************************************/
const uint8_t fract[] = {0,1,3,4,5,6,8,9};
/******************************************************************************************
 *	Deklaracje funkcji															 		 *
 *****************************************************************************************/
void mcp9801_write(uint8_t address, uint8_t data){
	twi_start();
	twi_write_byte(MCP9801);
	twi_write_byte(address);
	twi_write_byte(data);
	twi_stop();
}

uint8_t mcp9801_read(uint8_t address, uint8_t ack){
	uint8_t temp = 0;

	twi_start();
	twi_write_byte(MCP9801);
	twi_write_byte(address);
	twi_start();
	twi_write_byte(MCP9801 + 1);
	temp = twi_read_byte(ack);
	twi_stop();

	return temp;
}

void mcp9801_write_register(uint8_t address, uint8_t data){
	uint8_t temp = 0;

	temp = mcp9801_read(address, NOACK);

	temp |= data;

	mcp9801_write(address, temp);
}

void mcp9801_read_temp(uint8_t *temp_int, uint8_t *temp_fract){
	uint8_t temp[2];

	twi_start();
	twi_write_byte(MCP9801);
	twi_write_byte(TEMPERATURE);
	twi_start();
	twi_write_byte(MCP9801 + 1);
	temp[0] = twi_read_byte(ACK);
	temp[1] = twi_read_byte(NOACK);
	twi_stop();

	*temp_int = temp[0];
	temp[1] = temp[1]>>5;
	*temp_fract = fract[temp[1]];

/*	if((temp[1]>>4) & 0x08)
		*temp_fract = 5;
	else
		*temp_fract = 0;*/

}
/******************************************************************************************
 *	Koniec pliku mcp9801.c
 *****************************************************************************************/
